package com.socool;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.socool.manager.Manager_Shared;
import com.socool.manager.MySocketIO;

public class HomeActivity extends BaseActivity{


	String user_AccessToken;
	String user_Email;
	String user_ID;
	
	ProgressDialog progressDialog;
	static MySocketIO tos;
	
	private static final int REAUTH_ACTIVITY_CODE = 100;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(LOG_TAG, "["+getLocalClassName()+"]"+"onCreate");
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.content_frame);
		tos = new MySocketIO();
		uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);
	    
	    
	    progressDialog = ProgressDialog.show(this,"", "로그인중...");
	    Manager_Shared mManagerShared = new Manager_Shared(this);
		String isLogin = mManagerShared.getPref_LoginStatus();
	    Log.d(LOG_TAG, "["+getLocalClassName()+"]Login mode is "+isLogin);
	    if(isLogin.equals("facebook")){
	    	
	    	// Check for an open session
		    Session session = Session.getActiveSession();
		 
		    if(session !=null){
		    	Log.d(LOG_TAG, "["+getLocalClassName()+"session: "+session);	
		    	 if (session.isOpened()) {
				    	
				    	Log.d(LOG_TAG, "["+getLocalClassName()+"ssession is open");
				        // Get the user's data
				    	getUserInfo(session);
				    }else {
				    	Log.d(LOG_TAG, "["+getLocalClassName()+"ssession is not open");
					
				    }
		    	 
		    	 
		    	 
		    	 
		    }else{
		    	Log.d(LOG_TAG, "["+getLocalClassName()+"session is null");
		    }
		    
		   
	    }else if(isLogin.equals("normal")){
	    	
	    	
	    }
	  
	 
	  

		  Fragment newContent = new Frag_YourDates();
		    if (newContent != null){
		    	  replaceFragment(newContent,"Your Dates");
		    }
		    

			// 로그인 progressbar 없애기
			progressDialog.dismiss();
		
		
	}
	
	public void replaceFragment(Fragment fragment,String title) {
		
		getSupportFragmentManager()
		.beginTransaction()
		.replace(R.id.content_main, fragment)
		.commit();
		getSlidingMenu().showContent();
		setTitle(title);
		
	}
	public void addFragment(Fragment fragment,String title) {
		
		getSupportFragmentManager()
		.beginTransaction()
		.replace(R.id.content_main, fragment)
		.addToBackStack(null)
		.commit();
		getSlidingMenu().showContent();
		setTitle(title);
	}
	

	
	
	private void sendLoginInfo() {
		Log.d(LOG_TAG, "["+getLocalClassName()+"]"+"sendServer");
		
		try {
			
			
			
			
			JSONObject json = new JSONObject();
			json.put("accessToken", user_AccessToken);
			json.put("userID", user_ID);
			json.put("email", user_Email);
			
			
			tos.emit("AuthInfo",json);
			
			
		} catch (Exception e) {
			Log.d(LOG_TAG, "ERROR: "+e.getMessage());
		}
		
		
		
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    uiHelper.onResume();
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
	    super.onSaveInstanceState(bundle);
	    uiHelper.onSaveInstanceState(bundle);
	}

	@Override
	public void onPause() {
	    super.onPause();
	    uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	    tos.disconnect();
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    if (requestCode == REAUTH_ACTIVITY_CODE) {
	        uiHelper.onActivityResult(requestCode, resultCode, data);
	    }
	}
	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
	    if (session != null && session.isOpened()) {
	        // Get the user's data.
	    	getUserInfo(session);
	    }
	}
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(final Session session, final SessionState state, final Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	

	private void getUserInfo(final Session session) {
		
		Log.d(LOG_TAG, "["+getLocalClassName()+"]"+"getUserInfo()");
		
		// Make an API call to get user data and define a
		// new callback to handle the response.
		Request request = Request.newMeRequest(session,
				new Request.GraphUserCallback() {
			
					@Override
					public void onCompleted(GraphUser user, Response response) {
						// If the response is successful
						
						Log.d(LOG_TAG, "onCompleted");
						if (session == Session.getActiveSession()) {
					
							if (user != null) {
					
							
								// Set the id for the ProfilePictureView
								// view that in turn displays the profile
								// picture.
								try {

									user_AccessToken = session.getAccessToken();

									Log.d(LOG_TAG, "session.getAccessToken(): "
											+ user_AccessToken);
									Log.d(LOG_TAG,
											"session.getExpirationDate(): "
													+ session
															.getExpirationDate());

									user_ID = user.getId();
									Log.d(LOG_TAG, "user.getId: " + user_ID);
									JSONObject mJSONObject = user.getInnerJSONObject();
									
									
									
									user_Email = mJSONObject
											.getString("email");
									Log.d(LOG_TAG, "user.email: " + user_Email);
									Log.d(LOG_TAG, "mJSONObject: " + mJSONObject);
								} catch (Exception e) {
									
									Log.d(LOG_TAG, "ERROR: " + e.getMessage());
								}
								
								
								sendLoginInfo();
								

								
								
								

							}
						}
						if (response.getError() != null) {
							// Handle errors, will do so later.

						}
					}

				});
		request.executeAsync();
		Log.d(LOG_TAG, "["+getLocalClassName()+"]"+"request.executeAsync()");
	}

	

}

